package cn.zwx.business.order.controller;

import cn.zwx.base.constant.ResponseMsg;
import cn.zwx.base.enums.MqTopicEnum;
import cn.zwx.base.enums.RetCode;
import cn.zwx.base.util.Sequence;
import cn.zwx.business.order.mq.producer.DefaultProducer;
import cn.zwx.business.order.mq.producer.TransactionListenerImplForOrder;
import cn.zwx.business.order.mq.producer.TransactionProducer;
import cn.zwx.order.req.CreateOrderReq;
import cn.zwx.order.resp.CreateOrderResp;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.*;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description: 处理订单接口
 * @projectName:rocket-mq-example
 * @see:cn.zwx.business.order.controller
 * @author:zhangwenxue
 * @createTime:2020/10/15 13:31
 * @version:1.0
 */
@RestController
@RequestMapping("/order/v1")
public class OrderController {

    private static final Logger logger =  LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private TransactionProducer transactionProducer;

    @Autowired
    @Qualifier("transactionListenerImplForOrder")
    private TransactionListener transactionListener;

    @Autowired
    private DefaultProducer defaultProducer;

    /**
     * @description 创建订单接口
     * @return cn.zwx.base.constant.ResponseMsg
     * @author zhangwenxue
     * @createTime 2020/10/15 13:34
     **/
    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public ResponseMsg<CreateOrderResp> createOrder(@RequestBody CreateOrderReq req) throws MQClientException {
        //1.获取生产者
        TransactionMQProducer producer = transactionProducer.getProducer();
        //2.构建消息体
        String paramsStr = JSON.toJSONString(req);
        Message message = new Message(MqTopicEnum.ORDER_TOPIC.getTopic(), null, Sequence.createId(),paramsStr.getBytes());
        //3.发送消息
        //第一个参数可以理解成消费方需要的参数 第二个参数可以理解成消费方不需要 本地事务需要的参数
        producer.setTransactionListener(transactionListener);
        TransactionSendResult sendResult = producer.sendMessageInTransaction(message, req);
        logger.info("发送结果=%s, sendResult=%s \n", sendResult.getSendStatus(), sendResult.toString());
        //4.参数返回
        return this.getReturnObj(sendResult);

    }

    /**
     * @description 发送消息测试
     * @return cn.zwx.base.constant.ResponseMsg
     * @author zhangwenxue
     * @createTime 2020/10/15 13:34
     **/
    @RequestMapping(value = "/send",method = RequestMethod.POST)
    public ResponseMsg sendDefaultMsg() throws MQClientException, RemotingException, InterruptedException {
        Message message = new Message(MqTopicEnum.ORDER_SERVICE.getTopic(), null, Sequence.createId(),"defaultProducer".getBytes());
        defaultProducer.getProducer().send(message, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                logger.info("发送消息成功:{}",sendResult.getMessageQueue().getTopic());
            }

            @Override
            public void onException(Throwable e) {
               logger.info("发送消息异常:{}",e.getMessage());
            }
        });

        return ResponseMsg.success();
    }

    /**
     * @description  返回参数处理
     * @return cn.zwx.base.constant.ResponseMsg<cn.zwx.goods.resp.CreateOrderResp>
     * @author zhangwenxue
     * @createTime 2020/10/15 13:49
     **/
    private ResponseMsg<CreateOrderResp> getReturnObj(TransactionSendResult sendResult) {
        CreateOrderResp resp = new CreateOrderResp();
        if (SendStatus.SEND_OK == sendResult.getSendStatus()) {
            resp.setResultType(1);
            resp.setResultMsg("处理成功!");
            return ResponseMsg.success(resp);
        }else {
            resp.setResultType(2);
            resp.setResultMsg("处理失败!");
            return ResponseMsg.error(RetCode.FAIL,resp);
        }
    }

}
